<?php
namespace Content\Controller;

use Base\Controller\AdminBaseController;

class ModelController extends AdminBaseController{
	
	protected $modelModel;
	
	public function _initialize() {
		parent::_initialize();
		$this->modelModel = D("Content/Model");
	}
	
	/******************************** JSON *********************************/
	/** 添加信息 */
	public function save() {
		$modelJson = file_get_contents('php://input');
		$model = json_decode($modelJson, true);

		// setting
		$model['status'] = 1;

		// 执行添加
		$result = $this->modelModel->add($model);
		if (!$result) {
			$data['code'] = 499;
			$data['msg'] = '添加失败！';
			$this->ajaxReturn($data);
		}

		$newModel = $this->modelModel->where(array("id" => $result))->find();
			
		$data['code'] = 0;
		$data['msg'] = '添加成功！';
		$data['obj'] = $newModel;
		$this->ajaxReturn($data);
	}
	
	/** 查看所有  */
    public function getAll() {
		$result = $this->modelModel->select();
// 		dump($result);
		
	    // return
	    $this->ajaxReturn($result);
	}

	/** 查看所有列表 */
	public function dataList() {
		$_GET['notEqualMap'] = array('status' => -1);
		$dataList = $this->modelModel->dataList($_GET);
	    $this->ajaxReturn($dataList);
	}
	 
	/** 查看某信息 */
	public function find() {
		$id = $_GET['id'];
		
		$model = $this->modelModel->where(array("id" => $id))->find();
		if (!$model) {
			$data['code'] = 499;
			$data['msg'] = '未找到目标！';
			$this->ajaxReturn($data);
		}
		
	    $data['code'] = 0;
	    $data['msg'] = 'OK';
	    $data['obj'] = $model;
	    $this->ajaxReturn($data);
	}

	/** 修改某信息 */
	public function update() {
		$id = $_GET['id'];
		$modelJson = file_get_contents('php://input');
		$model = json_decode($modelJson, true);
		
		// 执行更新
		$result = $this->modelModel->where(array("id" => $id))->save($model);
		if (false === $result) {
			$data['code'] = 499;
			$data['msg'] = '编辑失败！';
			$this->ajaxReturn($data);
		}

		$updatedModel = $this->modelModel->where(array("id" => $id))->find();
			
		$data['code'] = 0;
		$data['msg'] = '编辑成功！';
		$data['obj'] = $updatedModel;
		$this->ajaxReturn($data);
	}
	
	/** 删除某信息 */
	public function delete() {
		$id = $_GET['id'];
		
		$model = $this->modelModel->where(array("id" => $id))->find();
		if (!$model) {
			$data['code'] = 499;
			$data['msg'] = '未找到目标！';
			$this->ajaxReturn($data);
		}
		
		// 更新status & update
		$model['status'] = -1;

		$result = $this->modelModel->where(array("id" => $id))->save($model);
		if (false === $result) {
			$data['code'] = 499;
			$data['msg'] = '删除失败！';
			$this->ajaxReturn($data);
		}
			
		$data['code'] = 0;
		$data['msg'] = '删除成功！';
		$this->ajaxReturn($data);
	}

	/******************************** HTML *********************************/
	/** index */
    public function index() {
		$this->display(':mode');
		return;
	}
	
}